import { Component, ElementRef, ViewChild } from '@angular/core';
import {ICellEditorAngularComp} from '@ag-grid-community/angular';
import { Constants } from '../../../utils/constants';

@Component({
  selector: 'apes-cell-textarea',
  template: `
      <textarea apes-input
                #textarea
                [(ngModel)]="inputValue"
                [rows]="rows"
                [cols]="cols"
                (blur)="onBlur()"
                (keydown)="onKeyDown($event)"
                [apesAutosize]="{ minRows: minRows, maxRows: maxRows }">
      </textarea>
     `,
  styles: []
})
export class EditorTextAreaComponent implements ICellEditorAngularComp {
  inputValue: any;
  params: any;
  ctx: any;
  rows = 100;
  cols = 100;
  minRows = 10;
  maxRows = 100;
  @ViewChild('textarea', { static: true }) textarea: ElementRef;

  constructor() {
  }

  agInit(params: any): void {
    this.params = params;
    this.inputValue = params.value;
    // this.ctx = params.context;
  }

  ngAfterViewInit() {
    setTimeout(() => {
      this.textarea.nativeElement.focus();
    }, 300);
  }
  isPopup(): boolean {
    return true;
  }

  getValue(): any {
    let result;
    if (!this.inputValue) {
      result = '';
      this.params.value = '';
    } else {
      result = this.inputValue;
      this.params.value = this.inputValue;
    }
    return result;
  }

  onKeyDown(event): void {
    let key = event.which || event.keyCode;
    if (key === 38 || key === 40) {
      this.preventDefaultAndPropagation(event);
    }else if (key == 13 || key == 9) {
      this.inputValue = event.target.value;
      this.params.value = event.target.value;
    }
    if (key == Constants.KEY_LEFT ||
      key == Constants.KEY_UP ||
      key == Constants.KEY_RIGHT ||
      key == Constants.KEY_DOWN ||
      (event.shiftKey && key == Constants.KEY_ENTER)) { // shift+enter allows for newlines
      event.stopPropagation();
    }
  }

  onBlur(): void {
    this.params.stopEditing(false);
  }

  private preventDefaultAndPropagation(event) {
    event.preventDefault();
    event.stopPropagation();
  }
}
